package com.qingke.easyjava.jdbc.command.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.qingke.easyjava.jdbc.app.BeSuperDao;
import com.qingke.easyjava.jdbc.command.PlayerCommand;
import com.qingke.easyjava.jdbc.pojo.Answer;
import com.qingke.easyjava.jdbc.pojo.Player;
import com.qingke.easyjava.jdbc.pojo.Question;
import com.qingke.easyjava.jdbc.util.QingkeConsole;

public class AnswerCommand extends PlayerCommand {

    public AnswerCommand(Player player) {
        super(player);
    }

    @Override
    public void executePlayerCommand() {
        int qid = QingkeConsole.askUserInputInt("请输入问题ID");
        
        BeSuperDao dao = new BeSuperDao();
        Question question = dao.getQuestion(qid);//一、
        
        if (question == null) {
            QingkeConsole.println("您输入的问题ID不存在！");
            return;
        }
        
        if (question.getFrom().getId() == player.getId()) {
            QingkeConsole.println("不允许回答自己提出的问题！");
            return;
        }

        String content = QingkeConsole.askUserInput("请输入您的回答");
        Answer answer = new Answer(-1, content, player);
        dao.upsertAnwser(answer);
        
        player.getAnswers().add(answer);
        question.getAnswers().add(answer);
        
    }
    // 一、
    /*    public Question getQuestion(long questionId) {
        Question question = null;
        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet rs = null;

        String sql = "SELECT id, value, player_id, isOpen, credit FROM question where id = ?";
        try {
            conn = getConnection();
            statement = conn.prepareStatement(sql);
            
            statement.setLong(1, questionId);
            
            rs = statement.executeQuery();
            
            while(rs.next()) {
                long id = rs.getInt("id");
                String value = rs.getString("value");
                long playerId = rs.getLong("player_id");
                int credit = rs.getInt("credit");
                boolean isOpen = "Y".equals(rs.getString("isOpen"));
                
                Player player = this.getPlayer(playerId);
                question = new Question(id, value, player, credit);
                question.setOpen(isOpen);

                List<Answer> answers = this.getAnswersFrom(question);
                question.setAnswers(answers);
            }

            return question;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cleanup(conn, statement, rs);
        }
        return question;
    }*/

}
